<?php
/**
 * +-------赛事列表控制器---------------------------+
 * +------------------------------------------------+
 * +------有赛事列表，比赛列表，比赛下的视频--------+
 * +------------------------------------------------+
 *
 * @author susy<susy.liang@ilongyuan.com.cn>
 */

namespace Home\Controller;

class MatchController extends HomeController {

    /**
     * 基础参数的初始化
     *@author susy.liang<liangling@ilongyuan.com.cn>
     */
    protected function _initialize() {
        parent::_initialize();

        $this->topicTitle = "热门赛事";
    }

    /**
     * 首页列表
     * 获取赛事列表数据
     *@author susy.liang<liangling@ilongyuan.com.cn>
     * modify by liubo<liubo@ilongyuan.com.cn> at 2016-04-21
     */
    public function index() {
        return $this->redirect(U('match/index'));
        $mevtObj = A( 'Api/Match', 'Event' );
        $total = $mevtObj->total();
        if ( $total ) {
            $listRow = C( 'MATCH_LISTS_NUM', NULL, 20 );
            $p = I( 'p', 1, 'intval' );
            $pager = I( 'pager', $listRow, 'intval' );

            $matches = $mevtObj->lists( $p, $pager );

            foreach ( $matches as $key => &$value ) {
                uri_format( $value['logo'] );
                uri_format( $value['cover'] );
            }

            $this->p = $p+1;//下一页码传给Js分页加载
        }

        $this->matches = $matches;
        $this->total = $total = count( $matches );
        $this->limit = $listRow;
        if ( IS_AJAX ) {
            $strHtml = $this->fetch( 'Template/Match/match' );

            $this->ajaxReturn( array( 'state'=>0, 'info'=>'操作成功',
                    'data'=>array( 'content'=>$strHtml, 'total'=>$total,
                        'limit'=>$listRow ) ) );
        }else {
            $hotData = $this->hotRace();
            foreach ($hotData as $key => &$value) {
                foreach ($value['list'] as $key1 => &$value1) {
                    uri_format( $value1['cover'] );
                    uri_format( $value1['match']['cover'] );
                }
            }
            $this->hotData = $hotData;
            $previewData = $this->_preview();
            foreach ($previewData as $key => &$value) {
                foreach ($value['list'] as $key1 => &$value1) {
                    uri_format( $value1['cover'] );
                    uri_format( $value1['match']['cover'] );
                }
            }
            $this->previewData = $previewData;
            C('DEFAULT_THEME', 'ui3');
            $this->assign('currentTab', 'match');
            $this->assign('title', '赛事');
            $this->display();
        }

    }

    /**
     * 赛事某个赛程下的比赛列表(原版本接口)
     * 默认获取最新赛程下的比赛
     * param type=all时取赛事下的所有比赛列表
     *@author susy.liang<liangling@ilongyuan.com.cn>
     */
    public function items() {

        $eventObj = A( 'Api/match', 'Event' );

        $id = I( 'id', 0, 'intval' );
        $match = $eventObj->info( $id );
        if ( empty( $match ) ) {
            $this->error( '赛事信息有误' );
        }

        $total = $eventObj->raceTotal(array('match_id'=>$id));
        if($total){

            uri_format( $match['teamlogo'] );

            $type = I('type');
            if($type != 'all'){
                $date = I( 'date', '' );
                if(!$date){
                     $defTime = $eventObj->getDefDate( $id );
                     $date = date( 'Y-m-d', $defTime );
                }
            }

            $p = I('p', 1, 'intval');
            $data = $this->getItems($id, $p, $match['teamlogo'], $date);

            $dates = $this->getDates( $id, 10, false );
            
            $this->races = $data;
            $this->dates = $dates;
            $this ->curDate = $date;
            $this->p = $p+1;//下一页码传给js加载
            $this->type = $type;
        }

        $this->match = $match;

        $this->display();

    }


    /**
    *获取赛事下的比赛
    *@param int $matchId 赛事的标识
    *@param string $defTeamLogo 赛事下默认的战队的logo
    *@return array
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    private function getItems($matchId=0, $p=1, $defTeamLogo='', $dateTime=0){

        $eventObj = A( 'Api/match', 'Event' );
        
        $limit = C('VIDOE_LIST_ROWS');
        $orderby = 'match_time desc, create_time desc';                      
        
        $map = array();
        $map['match_id'] = $matchId;
        $dateTime && $map['match_time'] = strtotime($dateTime);        
        
        $raceData = $eventObj->races( $map, $p, $limit, $orderby, '', true, $defTeamLogo );

        $data = array();
        if ( $raceData ) {
            $mapField = array( 'id', 'title', 'score', 'score_point', 'match_id', 'match_time', 'match_hour', 'team' );
            foreach ( $raceData as $key => $value ) {
                $data[] = $this->field_filter( $value, $mapField );
            }
        }
        return $data;
    }

    /**
    *ajax加载请求某一赛事下的比赛列表
    *根据param p 页码进行
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    public function ajaxItems(){

        $eventObj = A( 'Api/match', 'Event' );

        $id = I( 'id', 0, 'intval' );
        $match = $eventObj->info( $id );
        if ( empty( $match ) ) {
            $this->ajaxReturn(array('state'=>-1, 'info'=>'赛事信息有误'));
        }

        $total = $eventObj->raceTotal(array('match_id'=>$id));
        if($total){

            uri_format( $match['teamlogo'] );

            $type = I('type');
            if($type != 'all')
                $date = I( 'date', '' );
            
            $p = I('p', 1, 'intval');   
            $data = $this->getItems($id, $p, $match['teamlogo'], $date);

            $this->match = $match;
            $this->races = $data;
            $this->p = $p+1;//下一页码传给js分页
            $this->type = $type;
            $strHtml = $this->fetch('Template:races');
        }

        $this->ajaxReturn(array('state'=>0, 'info'=>'操作成功', 
                        'data'=>array('content'=>$strHtml,'total'=>count($data), 'limit'=>C('VIDOE_LIST_ROWS'))));
    }

    /**
     * 比赛详情
     * 即：比赛的视频明细信息
     *@author susy.liang<liangling@ilongyuan.com.cn>
     */
    public function detail() {
        $eventObj = A( 'Api/match', 'Event' );

        //$id = I( 'id', 0, 'intval' );
        $param = I('');
        $param = array_map('intval', $param);
        $id = $this->checkParam($param);

        $infos = $eventObj->video( $id, UID );
        if ( !$infos )
            $this->error( '比赛信息有误' );

        $this->matchId = $matchId = intval( $infos['match_id'] );
        $matches = $eventObj->info( $matchId );

        $this->matchTitle = $matches['title'];

        $fieldMap = array(
            'id', 'thumb', 'title', 'detail', 'score', 'total_score',
            'detail', 'create_time', 'videos', 'match_time', 'team',
            'game'
        );
        $infos = $this->field_filter( $infos, $fieldMap );

        if(UID){
            $infos['action']['is_favour'] =  intval( A('Api/Favour', 'Event')->isFavour(UID, $id) );
        }
        //取比赛的所有小比赛 modify by susy.liang 2015/8/19
       /* $map['id'] = $id;
        $map['match_id'] = $this->matchId;
        $raceData = $eventObj->races( $map, 0, 0, '', '', true, $matches['teamlogo'] );
        $data = array();
        if ( $raceData ) {
            $mapField = array('title', 'score', 'score_point', 'team' );
            $data = $this->field_filter( array_pop($raceData), $mapField );
        }
        $infos['match'] = $data;*/
        $map = array(
                'group_id'=>intval($infos['group_id']),
                'status'=>1,
            );
        $raceSchedule = D('Common/Video', 'Service')->where($map)->field('id,title,round')
                        ->order('round asc')->select();
        $schedule = array();
        foreach ($raceSchedule as $key => $value) {
            unset($value['_id']);
            array_push($schedule, $value);
        }
        $infos['schedule'] = $schedule;
        //end

        $objCtl = A( 'Home/Video', 'Controller' );
        $infos['comment'] = $objCtl->getComment( $id, 0, true );

        $infos['recommend'] = $this->getReferRace($infos['match_id'], $infos['group_id']);
        
        $this->data = $infos;

        $this->display();
    }

    /**
    *比赛视频明细参数检查 2015/8/19
    *@param array $data 请求的参数
    */
    private function checkParam($data=array()){
        if($data['race_id'])
        {
            $id = $data['race_id'];
        }
        elseif($data['group_id'])
        {
            $servObj = D('Common/Video', 'Service');
            $map = array(
                    'group_id'=>$data['group_id'],
                    'status'=>$servObj::STATUS_PASS,
                    'type'=>$servObj::TYPE_MATCH
                );
            $races = $servObj->where($map)->order('round asc')->getField('id', true);
            return intval($races[0]);
        }
        else
        {
            $this->error('参数错误');
        }

        return $id;
    }

    /**
    *相关的比赛推荐
    *
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    private function getReferRace($matchId=0, $raceId=0){

        $recommend = array();
        $fieldMap = array('id', 'title', 'subtitle', 'race_date', 
                    'race_hour', 'team', 'is_scribe', 'game', 'score'
                    );
        $recommend = A('Api/RaceGroup', 'Event')->getReferRace($matchId, $raceId);
        foreach ($recommend as $key => $value) {
            $value['game'] = $this->field_filter($value['game'], array('id','name','logo'));
            $value['score'] = $value['score']?array_map('intval', explode('-', $value['score'])):array();
            $recommend[$key] = $this->field_filter($value, $fieldMap);
        }

        return $recommend;
    }

    /**
     * 获取赛事下的比赛的赛时列表
     *
     * @author susy<susy.liang@ilongyuan.com.cn>
     */
    public function matchDate() {

        $id = I( 'id', 0, 'intval' );
        $res = $this->getDates( $id );

        if ( $res === false )
            $this->ajaxReturn( array( 'state'=>-1, 'info'=>'赛事信息有误' ) );
        else
            $this->ajaxReturn( array( 'state'=>0, 'info'=>'操作成功', 'data'=>array( 'content'=>$res ) ) );
    }

    /**
     * 获取dates
     *@author susy.liang<liangling@ilongyuan.com.cn>
     */
    private function getDates( $id, $pager, $needCheck=true ) {

        $eventObj = A( 'Api/match', 'Event' );
        $this->id = $id;

        if ( $needCheck ) {
            $match = $eventObj->info( $id );
            if ( empty( $match ) )
                return false;
        }

        if ( $pager ) {//列表

            return $eventObj->matchDate( $id, $pager );

        }else {//日历

            $this->dates = $eventObj->matchDate( $id, $pager, false );
            $strHtml = $this->fetch( 'Match:dates' );
        }

        return $strHtml;
    }

    /**
    *比赛的热门 2015/8/18
    *返回热门直播列表 以及 热门比赛列表
    *热门比赛按照时间降序，最多取前15天赛事的所有比赛
    *@author susy.liang<liangling@ilongyuan.com.cn>  
    */
    public function hot(){
        $liveData = $this->liveRace();
        $hotData = $this->hotRace();

        $data = array('live'=>$liveData, 'hot'=>$hotData);

        $this->data = $data;
        $this->display();
    }

    /**
    *热门比赛 2015/8/18
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    private function hotRace(){
        $data = array();

        $eventObj = A('Api/RaceGroup', 'Event');
        $videoEvent = A('Api/Video', 'Event');
        $curDate = date('Y-m-d', time());
        $map = array(
                'state'=>1,
                'race_date'=>array('lt', $curDate)
            );
        $ids = $eventObj->lists($map, 'id', C('VIDOE_LIST_ROWS'), 0, 'race_time desc');

        $fieldMap = array('id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'game', 'match', 'list', 'cover');
        foreach ($ids as $key => $value) {
            $detail = $eventObj->info($value['id']);
            $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):array();
            $detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
            $detail['match'] = $this->field_filter($detail['match'], array('id','title','cover'));
            $races = $videoEvent->lists(['group_id' => $detail['id'], 'type' => 1], 0, true);
            if (!empty($races) && is_array($races)) {
                sort($races);
                $races = array_slice($races, 0, 4);
            }
            $detail = $this->field_filter($detail, $fieldMap);
            $detail['races'] = $races;
            $race[$detail['race_date']][] = $detail;
        }

        foreach ($race as $key => $value) {
            $data[] = array('date'=>$key, 'list'=>$value);
        }

        return $data;
    }

    /**
    *直播赛 2015/8/18
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    private function liveRace(){
        $data = array();

        $eventObj = A('Api/RaceGroup', 'Event');
        $map = array('race_date'=>date('Y-m-d', time()));
        $ids = $eventObj->lists($map, 'id', 0, 0, 'race_time desc');

        foreach ($ids as $key => $value) {
            $detail = $eventObj->info($value['id']);
            $detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
            $detail['match'] = $this->field_filter($detail['match'], array('id','title','cover'));
            array_push($data, $detail);
        }

        return $data;
    }

    /**
    *预告赛接口 2015/8/18
    *以页码进行分页
    *@author susy.liang<liangling@ilongyuan.com.cn>
    * modify by liubo<liubo@ilongyuan.com.cn> at 2016-04-21
    */
    public function forcast(){

        $p = I('p', 1, 'intval');
        $pager = I('pager', C('VIDOE_LIST_ROWS'), 'intval');

        $this->data = $this->_preview($p, $pager);
        $this->display();
    }

    /**
    *赛事下的比赛列表 2015/8/18
    *取的是已经发布的比赛
    *以页码p进行分页
    *@author susy.liang<liangling@ilongyuan.com.cn>
    * modify by liubo<liubo@ilongyuan.com.cn> at 2016-04-21
    */
    public function races(){
        $eventObj = A('Api/match', 'Event');
        $videoEvent = A('Api/Video', 'Event');

        $id = I('id', 0, 'intval');
        $match = $eventObj->info($id);
        if(empty($match))
            $this->error('赛事信息有误');
        $this->match = $match;

        $matches = $eventObj->lists();
        foreach ( $matches as $key => $value ) {
            uri_format( $matches[$key]['logo'] );
            uri_format( $matches[$key]['cover'] );
        }
        $this->matchList = $matches;

        $p = I('p', 1, 'intval');
        $pager = I('pager', C('VIDOE_LIST_ROWS'), 'intval');

        $rgEventObj = A('Api/RaceGroup', 'Event');
        $raceDates = $rgEventObj->raceTimeGroup($id, $p, $pager);
        if($raceDates){
            $map = array(
                    'match_id'=>$id, 
                    'state'=>1,
                    'race_date'=>array('in', $raceDates)
                    );
            $ids = $rgEventObj->lists($map, 'id', 0, 0, 'race_time desc');

            $race = array();
            $fieldMap = array('id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'list', 'match', 'cover');
            foreach ($ids as $key => $value) {
                $detail = $rgEventObj->info($value['id'], $match['teamlogo']);
                $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):array();
                $detail = $this->field_filter($detail, $fieldMap);

                $races = $videoEvent->lists(['group_id' => $detail['id'], 'type' => 1], 0, true);
                if (!empty($races) && is_array($races)) {
                    sort($races);
                    $races = array_slice($races, 0, 4);
                }
                $detail['races'] = $races;
                uri_format( $detail['cover']);
                uri_format( $detail['match']['cover'] );

                $race[$detail['race_date']][] = $detail;
            }
            $data = array();
            foreach ($race as $key => $value) {
                $data[] = array('date'=>$key, 'list'=>$value);
            }
        }

        $this->races = $data;
        $this->p = $p;
        if(IS_AJAX){
            $htmlContent = $this->fetch('Template/Match/races');
            $res = array(
                    'content'=>$htmlContent,
                    'total'=>count($ids),
                    'limit'=>$pager
                );
            $this->ajaxReturn(array('state'=>0, 'info'=>'操作成功', 'data'=>$res));
        }else{
            C('DEFAULT_THEME', 'ui3');
            $this->assign('currentTab', 'match');
            $this->assign('title', $match['title']);
            $this->id = $id;
            $this->display();
        }
    }

    public function recentResult() {
        $id = I('id', 0, 'intval');

        if (empty($id)) {
            $this->ajaxReturn(array('state'=>-1, 'info'=>'赛事信息有误'));
        }

        $eventObj = A('Api/video', 'Event');
        $result = $eventObj->getRecentResult($id);

        $this->ajaxReturn(array('state'=>0, 'info'=>'操作成功', 'data'=>$result));
    }

    /**
     * 赛事预告数据
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function _preview($p = 1, $pager = 0) {
        !$pager && $pager = C('VIDOE_LIST_ROWS');

        $data = array();
        $eventObj = A('Api/RaceGroup', 'Event');
        $scribeObj = A('Api/RaceScribe', 'Event');

        $map = array(
                'race_date'=>array('gt', date('Y-m-d', time())),
                'status'=>1
            );

        $ids = $eventObj->lists($map, 'id', $pager, $p, 'race_time asc');

        $fieldMap = array('id', 'title', 'subtitle', 'race_date', 
                    'race_hour', 'team', 'is_scribe', 'game', 'match', 'cover'
                    );
        $items = array();
        foreach ($ids as $key => $value) {
            $detail = $eventObj->info($value['id']);
            $detail['is_scribe'] = intval($scribeObj->is_scribe(UID, $value['id']));
            $detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
            $detail = $this->field_filter($detail, $fieldMap);
            $items[$detail['race_date']][] = $detail;

        }

        foreach ($items as $key => $value) {
            $data[] = array('date'=>$key, 'list'=>$value);
        }
        return $data;
    }
}